package com.utcook.host.fragmentdialog

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.Observable
import androidx.fragment.app.Fragment
import com.utcook.host.fragmentdialog.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityMainBinding
    private val viewModel = MainViewModel()
    
    private var recipeFragment = RecipeFragment()
    private var ingredientsFragment = IngredientsFragment()
    private var settingsFragment = SettingsFragment()
    private var currentFragment: Fragment? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 隐藏标题栏
        supportActionBar?.hide()
        
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        binding.activity = this
        binding.viewModel = viewModel
        
        // 设置Fragment切换监听
        setupFragmentListener()
        
        // 初始化Fragment
        if (savedInstanceState == null) {
            // 首次创建，初始化所有Fragment
            initializeFragments()
            showFragment(recipeFragment)
        } else {
            // 屏幕旋转后恢复，重新获取Fragment引用
            restoreFragments()
        }
    }
    
    private fun setupFragmentListener() {
        viewModel.selectedTabIndex.addOnPropertyChangedCallback(object : Observable.OnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                when (viewModel.selectedTabIndex.get()) {
                    0 -> showFragment(recipeFragment)
                    1 -> showFragment(ingredientsFragment)
                    2 -> showFragment(settingsFragment)
                }
            }
        })
    }
    
    private fun initializeFragments() {
        val transaction = supportFragmentManager.beginTransaction()
        
        // 添加所有Fragment，但只显示第一个
        transaction.add(R.id.fragment_container, recipeFragment, "recipe")
        transaction.add(R.id.fragment_container, ingredientsFragment, "ingredients")
        transaction.add(R.id.fragment_container, settingsFragment, "settings")
        
        // 隐藏除了第一个之外的所有Fragment
        transaction.hide(ingredientsFragment)
        transaction.hide(settingsFragment)
        
        transaction.commit()
        currentFragment = recipeFragment
    }
    
    private fun restoreFragments() {
        // 从FragmentManager中恢复Fragment引用
        recipeFragment = supportFragmentManager.findFragmentByTag("recipe") as? RecipeFragment ?: RecipeFragment()
        ingredientsFragment = supportFragmentManager.findFragmentByTag("ingredients") as? IngredientsFragment ?: IngredientsFragment()
        settingsFragment = supportFragmentManager.findFragmentByTag("settings") as? SettingsFragment ?: SettingsFragment()
        
        // 确定当前显示的Fragment
        currentFragment = when (viewModel.selectedTabIndex.get()) {
            0 -> recipeFragment
            1 -> ingredientsFragment
            2 -> settingsFragment
            else -> recipeFragment
        }
        
        // 确保所有Fragment都已添加
        if (supportFragmentManager.findFragmentByTag("recipe") == null) {
            val transaction = supportFragmentManager.beginTransaction()
            transaction.add(R.id.fragment_container, recipeFragment, "recipe")
            transaction.add(R.id.fragment_container, ingredientsFragment, "ingredients")
            transaction.add(R.id.fragment_container, settingsFragment, "settings")
            transaction.commit()
        }
        
        // 根据当前选中的tab显示对应的Fragment
        currentFragment?.let { showFragment(it) }
    }
    
    private fun showFragment(fragment: Fragment) {
        if (currentFragment == fragment) return
        
        val transaction = supportFragmentManager.beginTransaction()
        
        // 隐藏所有Fragment
        transaction.hide(recipeFragment)
        transaction.hide(ingredientsFragment)
        transaction.hide(settingsFragment)
        
        // 显示目标Fragment
        transaction.show(fragment)
        
        transaction.commit()
        currentFragment = fragment
    }
}